﻿using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.EventSystems;
using UnityEngine.UI;

/// <summary>
/// 面板基类
/// 找到所有自己面板下的控件对象
/// 它应该要提供显示和隐藏的行为
/// </summary>
public class BasePanel : MonoBehaviour
{

    private Dictionary<string, List<UIBehaviour>> compDic = new Dictionary<string, List<UIBehaviour>>();
    protected virtual void Awake()
    {
        FindChildrenComp<Button>();
        FindChildrenComp<Image>();
        FindChildrenComp<Slider>();
        FindChildrenComp<Text>();
        FindChildrenComp<Scrollbar>();
        FindChildrenComp<ScrollRect>();
        FindChildrenComp<Toggle>();
        FindChildrenComp<InputField>();
    }
    /// <summary>
    /// 得到对应名字的对应控件脚本
    /// </summary>
    /// <typeparam name="T"></typeparam>
    /// <param name="compName"></param>
    /// <returns></returns>
    protected T GetComp<T>(string compName) where T : UIBehaviour
    {
        if (compDic.ContainsKey(compName))
        {
            for (int i = 0; i < compDic[compName].Count; i++)
            {
                if (compDic[compName][i] is T)
                {
                    return compDic[compName][i] as T;
                }
            }
        }
        return null;
    }

    /// <summary>
    /// 显示自己的虚方法
    /// </summary>
    public virtual void ShowMe()
    {
    }
    /// <summary>
    /// 隐藏自己的虚方法
    /// </summary>
    public virtual void HideMe()
    {
    }

    protected virtual void OnClick(string btnName)
    {
    }

    protected virtual void OnValueChanged(string toggleName,bool value)
    {
    }

    /// <summary>
    /// 找到所有控件并存入控件字典的方法
    /// </summary>
    /// <typeparam name="T"></typeparam>
    private void FindChildrenComp<T>() where T : UIBehaviour
    {
        T[] comps = this.GetComponentsInChildren<T>();
        for (int i = 0; i < comps.Length; i++)
        {
            string objName = comps[i].gameObject.name;
            if (compDic.ContainsKey(objName))
            {
                compDic[objName].Add(comps[i]);
            }
            else
            {
                compDic.Add(objName, new List<UIBehaviour>() { comps[i] });
            }
            if (comps[i] is Button)
            {
                (comps[i] as Button).onClick.AddListener(()=> {
                    OnClick(objName);
                });
            }
            if (comps[i] is Toggle)
            {
                (comps[i] as Toggle).onValueChanged.AddListener((value) => {
                    OnValueChanged(objName,value);
                });
            }

        }
        
    }

    
}
